package com.bootdo.system.controller;

import com.bootdo.blog.domain.ContentDO;
import com.bootdo.blog.service.ContentService;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.domain.FileDO;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.service.FileService;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.hjh.cache.MemberCache;
import com.bootdo.hjh.service.PointsService;
import com.bootdo.oa.service.NotifyService;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	MenuService menuService;
	@Autowired
	FileService fileService;
	@Autowired
	private PointsService pointsService;

	@Autowired
	ContentService bContentService;

	@Autowired
	MemberCache memberCache;

	@Autowired
	UserDao userDao;

	@Autowired
	private NotifyService notifyService;

	@GetMapping({ "/", "" })
	String welcome(Model model) {
		 Subject subject = SecurityUtils.getSubject();
	     Object obj = subject.getPrincipal();
	     Long userId = ((UserDO)obj).getUserId();
		logger.info("用户首页");

		//首页公告
//		List<ContentDO> bContentList = bContentService.listGongGao(0,4);
		Map<String, Object> notifyQuery = new HashMap<>();
		notifyQuery.put("offset", 0);
		notifyQuery.put("limit", 4);
		notifyQuery.put("userId", userId);
		PageUtils pageUtils = notifyService.selfList(notifyQuery);

		model.addAttribute("contentList", pageUtils.getRows());

		//现金积分总金额
		Integer cashPointsTotal = pointsService.cashPointsTotal(userId);
		model.addAttribute("cashPointsTotal", cashPointsTotal);
		//商品积分总金额
		Integer productPointsTotal = pointsService.productPointsTotal(userId);
		model.addAttribute("productPointsTotal", productPointsTotal);
//		//第一层直推人数
//		model.addAttribute("firstFloorNum", memberCache.countFirstRecommend(userId));
//		//第二层直推人数
//		model.addAttribute("secondFloorNum", memberCache.countSecondRecommend(userId));
		model.addAttribute("superior", memberCache.superiorTrueName(userId));

		UserDO me = userDao.get(userId);
		model.addAttribute("me", me);
		return "hjh/index";
	}

	@Log("请求访问主页")
	@GetMapping({ "/admin" })
	String index(Model model) {
		List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
		model.addAttribute("menus", menus);
		model.addAttribute("name", getUser().getName());
		FileDO fileDO = fileService.get(getUser().getPicId());
		if(fileDO!=null&&fileDO.getUrl()!=null){
			if(fileService.isExist(fileDO.getUrl())){
				model.addAttribute("picUrl",fileDO.getUrl());
			}else {
				model.addAttribute("picUrl","/img/photo_s.jpg");
			}
		}else {
			model.addAttribute("picUrl","/img/photo_s.jpg");
		}
		model.addAttribute("username", getUser().getUsername());
		return "index_v1";
	}

	@GetMapping("/login")
	String login() {
		logger.info("请求登录页面");
		return "/login";
	}

	@Log("管理员登录")
	@PostMapping("/login")
	@ResponseBody
	R ajaxLogin(String username, String password) {
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			token.setRememberMe(true);
			subject.login(token);
			subject.getSession().setAttribute("user",subject.getPrincipal());
			R r = R.ok();
			r.put("user",subject.getPrincipal());
			return r;
		} catch (AuthenticationException e) {
			return R.error("用户或密码错误");
		}
	}

	@Log("普通用户登录")
	@PostMapping("/general_login")
	@ResponseBody
	R userAjaxLogin(String username, String password) {
		logger.info("前端用户登录");
		password = MD5Utils.encrypt(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			return R.ok();
		} catch (AuthenticationException e) {
			return R.error("用户或密码错误");
		}
	}

	@GetMapping("/gonggao")
	String gonggaoDetail(@RequestParam("cid") Long cid,Model model){
		ContentDO content = bContentService.get(cid);
		model.addAttribute("content",content);
		return "hjh/gonggao";
	}

	@GetMapping("/logout")
	String logout() {
		logger.info("退出");
		ShiroUtils.logout();
		return "redirect:/admin";
	}

	@GetMapping("/main")
	String main() {
		return "main";
	}


	@GetMapping("/general/index")
	String generalMain() {
		return "hjh/index";
	}

	@GetMapping("/403")
	String error403() {
		return "403";
	}

}
